package jee.forum.controller;

import javax.ejb.Stateful;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpSession;
import jee.forum.entities.User;
import org.apache.log4j.Logger;

/**
 * @author Tobi
 */
@Stateful
@LocalBean
public class SessionController {

    Logger log = Logger.getLogger(SessionController.class);
    @PersistenceContext
    private EntityManager em;

    User user;
    HttpSession session;

    public void setSession(HttpSession session) {
        this.session = session;
    }

    public HttpSession getSession() {
        return session;
    }
    
    public boolean login(String username, String password) throws Exception {

        log.info("Search for user in DB");

        try {

            Query q = em.createNamedQuery("Userlogin");
            
            q.setParameter("username", username);
            q.setParameter("password", password);
            user = (User) q.getSingleResult();

        } catch (NoResultException nre) {
            log.info("User nicht in der DB auffindbar" + nre.getMessage());
            return false;
        }

        log.info("User" + user.getUsername() + "gefunden");
        return true;


    }
}
